const Koa    = require('koa');
const Router = require('koa-router');
const fs     = require('fs');
const bodyParser = require('koa-bodyparser');

const app    = new Koa();
app.use(bodyParser());


async function render(page){
    return new Promise((resolve, reject) => {
        let view = './view/' + page;
        fs.readFile(view, 'binary', (err, data) => {
            if(err){
                reject(err);
            }else{
                resolve(data);
            }
        })
    })
}

async function parsePostStr(post_str){
    let post_data = {};
    let post_str_list = post_str.split('&');
    console.log(post_str_list);
    for(i = 0; i < post_str_list.length; i++){
        let item_list = post_str_list[i].split('=');
        post_data[item_list[0]] = item_list[1];
    }
    return post_data;
}

async function parsePostData(ctx){
    return new Promise((resolve, reject) => {
        try{
            let post_str = '';
            ctx.req.addListener('data', (data) => {
                post_str += data;
            })
            ctx.req.addListener('end', function(){
                let parse_data = parsePostStr(post_str);
                resolve(parse_data);
            })
        }catch(err){
            reject(err);
        }
    })
}

//子路由1
let home = new Router();
home.get('/', async(ctx) => {
    console.log('./');
    let html = await render('index.html');
    ctx.body = html;
}).get('index.html', async(ctx) => {
    console.log('index.html');
    ctx.body = await render('index.html');
})

//子路由2
let view = new Router();
view.get('404.html', async(ctx) => {
    console.log('404.html');
    ctx.body = await render('404.html');
}).get('todo.html', async(ctx) => {
    console.log('/todo.html')
    ctx.body = await render('todo.html');
}).get('post.html', async(ctx) => {
    console.log('/post.html');
    ctx.body = await render('post.html');
})

view.post('postAdd', async(ctx) => {
    let parse_data = ctx.request.body;
    //let parse_data = await parsePostData(ctx);
    console.log(parse_data);
    ctx.body = parse_data;
})

//console.log(render('index.html'));

//装载所有子路由
let router = new Router();
//此处路由路径和view.get、home.get结合，对应html页面中链接路径
//路由路径非绝对路径，注意区分
router.use('/', home.routes(), home.allowedMethods());
router.use('/', view.routes(), view.allowedMethods());

//加载路由中间件
app.use(router.routes()).use(router.allowedMethods());


app.listen(3000, () => {
    console.log('starting...');
})
